import GameConfig from "../../GameConfig";
import UILangData, { SimpleLangData } from "../base/UILangData";
import AudioExt from "../ccExt/AudioExt";


const { ccclass, property, menu } = cc._decorator;

@ccclass
@menu('GlobalUI/MessageBox')
export default class MessageBox extends yy.MessageBox {

	// 背景遮罩(遮罩透明度统一+增加淡入淡出动画)
	@property(cc.Node)
	private readonly blackMask: cc.Node = null;

	@property(cc.Animation)
	private readonly anim: cc.Animation = null;

	@property(cc.AnimationClip)
	private readonly AniShow: cc.AnimationClip = null;

	@property(cc.AnimationClip)
	private readonly AniHide: cc.AnimationClip = null;

	// 消息框标题
	@property(cc.Label)
	private readonly title: cc.Label = null;
	@property
	private readonly titleDecor: string = '-';
	// 消息框内容（富文本）
	@property(cc.RichText)
	private readonly richText: cc.RichText = null;

	// 确定按钮
	@property(cc.Node)
	private readonly btnYes: cc.Node = null;
	@property(cc.Label)
	private readonly tipsYes: cc.Label = null;
	@property(cc.Node)
	private readonly adYes: cc.Node = null;

	// 取消按钮
	@property(cc.Node)
	private readonly btnCancel: cc.Node = null;
	@property(cc.Label)
	private readonly tipsCancel: cc.Label = null;
	@property(cc.Node)
	private readonly adCancel: cc.Node = null;

	// 确认取消按钮父容器
	@property(cc.Node)
	private readonly btnContiner: cc.Node = null;
	// 单按钮（ok按钮）
	@property(cc.Node)
	private readonly btnOK: cc.Node = null;
	@property(cc.Label)
	private readonly tipsOk: cc.Label = null;
	@property(cc.Node)
	private readonly adOk: cc.Node = null;

	// 关闭按钮
	@property(cc.Node)
	private readonly btnClose: cc.Node = null;

	// 测试文本
	@property(cc.RichText)
	private readonly cloneLabel: cc.RichText = null;


	// 消息框多语言信息
	private _langData: UILangData = null;


	onLoad() {
		this.initLangData();
		this.btnYes.getComponent(cc.Button).enableAutoGrayEffect = false;
		this.btnCancel.getComponent(cc.Button).enableAutoGrayEffect = false;
		this.btnOK.getComponent(cc.Button).enableAutoGrayEffect = false;
	}

	private initLangData() {
		this._langData = new UILangData(GameConfig.langList, 'en');
		const json: SimpleLangData = {
			"msgtitle": {
				"en": "System Message",
				"zh": "系统消息",
				"zhf": "系統消息",
				"jp": "システムメッセージ",
				"id": "Pesan Sistem",
				"hi": "सिस्टम संदेश",
				"pt": "Mensagem do Sistema",
				"es": "Mensaje del Sistema",
				"ru": "Системное сообщение",
				"ar": "رسالة النظام",
				"ms": "Mesej Sistem",
				"my": "စနစ် မက်ဆေ့ဂျ်",
				"th": "ข้อความระบบ",
				"vi": "Thông tin hệ thống"
			},
			"confirm": {
				"en": "Confirm",
				"zh": "确定",
				"zhf": "確定",
				"jp": "確認",
				"id": "Konfirmasi",
				"hi": "पुष्टि करें",
				"pt": "Confirmar",
				"es": "Confirmar",
				"ru": "Подтвердить",
				"ar": "تأكيد",
				"ms": "Sahkan",
				"my": "အတည်ပြုရန်",
				"th": "ยืนยัน",
				"vi": "Xác nhận."
			},
			"cancel": {
				"en": "Cancel",
				"zh": "取消",
				"zhf": "取消",
				"jp": "キャンセル",
				"id": "Batal",
				"hi": "रद्द करें",
				"pt": "Cancelar",
				"es": "Cancelar",
				"ru": "Отмена",
				"ar": "إلغاء",
				"ms": "Batal",
				"my": "ပယ်ဖျက်ရန်",
				"th": "ยกเลิก",
				"vi": "Hủy"
			}
		};
		this._langData.setJsonLangData(json);
	}

	/**
	* 初始化MessageBox,该函数在onLoad之后，show之前调用
	*/
	private isAnimating: boolean = false;
	private data: yy.MessageBoxData;
	public initMessageBox(data: yy.MessageBoxData): any {
		this.data = data;
		// 按钮名称特殊处理校验
		let btnNames: Array<string> = new Array();
		if (data.param) {
			const tempList: Array<string> = data.param as Array<string>;
			if (tempList && tempList.length > 1) {
				const checkStr: string = tempList[0].toLowerCase().trim();
				const len = tempList.length;
				if (checkStr == "btnname") {
					for (let index = 1; index < len; index++) {
						const name = tempList[index];
						btnNames.push(name);
					}
				}
			}
		}
		let titleStr: string = this._langData.getString("msgtitle");
		if (!!titleStr && titleStr.length > 0)
			titleStr = this.titleDecor + ' ' + titleStr + ' ' + this.titleDecor
		this.title.string = titleStr;
		// 设置文本
		if (data.name && data.name.length > 0) {
			this.title.string = '- ' + data.name + ' -';
		}
		this.richText.horizontalAlign = cc.macro.TextAlignment.CENTER;
		this.richText.string = data.text;
		this.cloneLabel.string = data.text;
		//@ts-ignore
		this.richText._updateRichText();
		//@ts-ignore
		this.cloneLabel._updateRichText();
		this.scheduleOnce((() => {
			if (this.richText.node.height >= this.richText.lineHeight * 2) {
				if (this.cloneLabel.node.width < this.richText.node.width) {
					this.richText.horizontalAlign = cc.macro.TextAlignment.CENTER;
				} else {
					this.richText.horizontalAlign = cc.macro.TextAlignment.LEFT;
				}
			}

		}).bind(this), 0);
		if (data.btnType == yy.MBBtnType.Yes) {
			this.btnContiner.active = false;
			this.btnOK.active = true;
			// 按鈕文字，新增需求，需要處理AD圖標顯示 <img src='ad' />
			let btnStr: string = btnNames.length > 0 ? btnNames[0] : this._langData.getString("confirm")
			const obj = MessageBox.dealBtnStrAD(btnStr);
			btnStr = obj.txt;
			this.tipsOk.string = btnStr;
			if (this.adOk)
				this.adOk.active = obj.hasAd;
		}
		else if (data.btnType == yy.MBBtnType.YesNo || data.btnType == yy.MBBtnType.YesNoCancel) {
			this.btnContiner.active = true;
			this.btnOK.active = false;
			// yes tips 按鈕文字，新增需求，需要處理AD圖標顯示 <img src='ad' />
			let yesStr: string = btnNames.length > 0 ? btnNames[0] : this._langData.getString("confirm");
			const objYes = MessageBox.dealBtnStrAD(yesStr);
			yesStr = objYes.txt;
			this.tipsYes.string = yesStr;
			if (this.adYes)
				this.adYes.active = objYes.hasAd;
			// cancel tips 按鈕文字，新增需求，需要處理AD圖標顯示 <img src='ad' />
			let noStr: string = btnNames.length > 1 ? btnNames[1] : this._langData.getString("cancel");
			const objNo = MessageBox.dealBtnStrAD(noStr);
			noStr = objNo.txt;
			this.tipsCancel.string = noStr;
			if (this.adCancel)
				this.adCancel.active = objNo.hasAd;
		}
	}

	// 檢測是否有<img src='ad' />標籤（不區分大小寫和空格）
	static dealBtnStrAD(str: string): { hasAd: boolean, txt: string } {
		let hasAd = false;
		let txt = str;
		if (!str || str.length == 0)
			return { hasAd, txt };
		// 指定AD標籤不少於15個字符
		if (str.length >= 15) {
			const patt1 = /<img\s+src=('|")ad('|")\/?.+?>/i;
			hasAd = str.search(patt1) >= 0;
		}
		// 移除所有富文本標籤（按鈕文字不支持富文本），並清除行首行末可能由標籤造成的空格
		txt = str.replace(/<\/?.+?>/g, "").trim();
		return { hasAd, txt };
	}

	/**
	 * 显示该框,一般用来播放显示动画
	 */
	public show() {
		// cc.log('MessageBox show act, isAnimating =', this.isAnimating);
		if (this.isAnimating)
			return;
		AudioExt.playEffect('MenuShow');
		this.isAnimating = true;
		this.btnYes.getComponent(cc.Button).interactable = true;
		this.btnCancel.getComponent(cc.Button).interactable = true;
		this.btnOK.getComponent(cc.Button).interactable = true;
		//
		this.anim.node.opacity = 0;
		this.node.active = true;
		this.anim.play(this.AniShow.name);
		this.anim.on('finished', this.onShowCompleted, this);
		// 背景遮罩动画
		if (this.blackMask) {
			this.blackMask.opacity = 0;
			this.blackMask.stopAllActions();
			cc.tween(this.blackMask)
				.to(0.21, { opacity: 220 })
				.start();
		}
	}
	private onShowCompleted() {
		this.isAnimating = false;
		this.anim.off('finished', this.onShowCompleted, this);
	}

	/**
	 * 隐藏该框，注意，隐藏完成后(动画播放完成)，请主动调用this.onHideEnd();函数
	 *
	 */
	public hide() {
		if (this.data && this.data.param && this.data.param["lobbyHasNewVersion"]) return;
		if (this.isAnimating)
			return;
		AudioExt.playEffect('MenuClose');

		this.isAnimating = true;
		this.btnYes.getComponent(cc.Button).interactable = false;
		this.btnCancel.getComponent(cc.Button).interactable = false;
		this.btnOK.getComponent(cc.Button).interactable = false;
		this.anim.play(this.AniHide.name);
		this.anim.on('finished', this.onAnimCompleted, this);
		// 背景遮罩动画
		if (this.blackMask) {
			this.blackMask.stopAllActions();
			cc.tween(this.blackMask)
				.to(0.21, { opacity: 0 })
				.start();
		}
	}

	private onAnimCompleted() {
		this.isAnimating = false;
		this.anim.off('finished', this.onAnimCompleted, this);
		this.node.active = false;
		this.onHideEnd();
		// cc.log('MessageBox onAnimCompleted, isAnimating =', this.isAnimating);
	}
}
